#!/bin/bash
set -e

PYTHON_VERSION="3.10.13"
OUTPUT_DIR="python-offline-debian-aarch64"
INSTALL_DIR="/opt/python310"
DEBIAN_VERSION=$(lsb_release -cs)

echo "创建离线安装包: Python ${PYTHON_VERSION} for Debian ${DEBIAN_VERSION} (aarch64)"

# 创建三个子目录结构 src, deps, install_script
mkdir -p ${OUTPUT_DIR}
cd ${OUTPUT_DIR}
mkdir -p src deps install_script


# 1. 下载 Python 源码
echo "下载 Python ${PYTHON_VERSION} 源码..."

wget -P src/ https://mirrors.aliyun.com/python-release/source/Python-${PYTHON_VERSION}.tar.xz

# 2. 下载编译依赖 (Debian 特定)
echo "下载编译依赖..."
sudo apt-get update
sudo apt-get download $(apt-cache depends --recurse --no-recommends --no-suggests \
  --no-conflicts --no-breaks --no-replaces --no-enhances \
  --no-pre-depends build-essential zlib1g-dev libncurses5-dev \
  libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev \
  libsqlite3-dev libbz2-dev liblzma-dev libgdbm-compat-dev \
  | grep "^\w" | grep -v "i386" | sort -u)

# 3. 移动依赖包
mv *.deb deps/

# 4. 生成安装脚本
cat > install_script/install.sh << 'EOF'
#!/bin/bash
set -e

PYTHON_VERSION="3.10.13"

SCRIPT_DIR=$(cd $(dirname "$0") && pwd)
TMP_ROOT="/tmp/python-offline-install"
INSTALL_DIR="/opt/python310"  # 独立安装目录

# 检测系统信息
detect_system() {
    echo "系统信息:"
    echo "架构: $(uname -m)"
    echo "发行版: $(lsb_release -ds)"
    echo "内核: $(uname -r)"
}

# 检测已有 Python
detect_python() {
    echo "已安装的 Python 版本:"
    command -v python && python --version || echo "未找到系统 Python"
    command -v python3 && python3 --version || echo "未找到系统 Python3"
}

# 准备安装环境
prepare_environment() {
    echo "准备安装环境..."
    sudo rm -rf ${TMP_ROOT}
    mkdir -p ${TMP_ROOT}/{deps,src}
    sudo mkdir -p ${INSTALL_DIR}
    
    # 复制资源
    cp -r ${SCRIPT_DIR}/../src/* ${TMP_ROOT}/src/
    cp -r ${SCRIPT_DIR}/../deps/* ${TMP_ROOT}/deps/
}

# 安装依赖
install_dependencies() {
    echo "[1/5] 安装编译依赖..."
    # 检查是否已安装开发工具
    if ! dpkg -l | grep -q "build-essential"; then
        echo "安装构建工具..."
        sudo dpkg -i ${TMP_ROOT}/deps/*.deb || true
        sudo apt-get -f install -y
    else
        echo "构建工具已安装，跳过依赖安装"
    fi
    
    # 安装特定依赖
    for pkg in zlib1g-dev libssl-dev libffi-dev libsqlite3-dev liblzma-dev; do
        if ! dpkg -l | grep -q "$pkg"; then
            echo "安装 $pkg..."
            sudo dpkg -i ${TMP_ROOT}/deps/${pkg}*.deb || true
        fi
    done
}

# 编译 Python
compile_python() {
    echo "[2/5] 编译 Python ${PYTHON_VERSION}..."
    tar -Jxvf ${TMP_ROOT}/src/Python-*.tar.xz -C ${TMP_ROOT}/src
    cd ${TMP_ROOT}/src/Python-${PYTHON_VERSION}
    
    # Debian 特定优化参数
    ./configure \
        --prefix=${INSTALL_DIR} \
        --enable-optimizations \
        --enable-shared
    
    # 根据内存调整编译并行度
    MEM_GB=$(free -g | awk '/Mem:/ {print $2}')
    if [ $MEM_GB -lt 2 ]; then
        MAKE_JOBS=1
    elif [ $MEM_GB -lt 4 ]; then
        MAKE_JOBS=2
    else
        MAKE_JOBS=$(nproc)
    fi
    
    echo "使用 ${MAKE_JOBS} 个并行任务编译..."
    make -j${MAKE_JOBS}
    echo "编译完成，开始安装..."
    sudo make altinstall
}

# 配置环境
configure_environment() {
    echo "[3/5] 配置环境..."
    # 创建版本化链接
    sudo ln -sf ${INSTALL_DIR}/bin/python3.10 /usr/local/bin/python3.10
    sudo ln -sf ${INSTALL_DIR}/bin/pip3.10 /usr/local/bin/pip3.10
    
    # 更新动态链接库缓存
    sudo ldconfig
    
    # 配置替代方案
    if command -v update-alternatives &> /dev/null; then
        echo "设置 Python 替代方案..."
        sudo update-alternatives --install /usr/bin/python python /usr/local/bin/python3.10 100
        sudo update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.10 100
    fi
}

# 验证安装
verify_installation() {
    echo "[4/5] 验证安装..."
    ${INSTALL_DIR}/bin/python3.10 --version
    ${INSTALL_DIR}/bin/pip3.10 --version
    
    echo "测试模块导入..."
    ${INSTALL_DIR}/bin/python3.10 -c "import ssl; import sqlite3; import zlib; print('核心模块加载成功')"
    
    echo "安装成功！Python 3.10 已安装到 ${INSTALL_DIR}"
    echo "使用: python3.10 或 /opt/python310/bin/python3.10"
}

# 主安装流程
detect_system
detect_python
prepare_environment
#install_dependencies
compile_python
configure_environment
verify_installation
EOF

# 5. 打包
chmod +x install_script/install.sh
cd ..
tar -czf python-offline-debian-aarch64-${PYTHON_VERSION}.tar.gz ${OUTPUT_DIR}

echo "离线包创建完成: python-offline-debian-aarch64-${PYTHON_VERSION}.tar.gz"
echo "大小: $(du -sh python-offline-debian-aarch64-${PYTHON_VERSION}.tar.gz | awk '{print $1}')"
echo "将此文件复制到目标机器并运行:"
echo "  tar -xzf python-offline-debian-aarch64-${PYTHON_VERSION}.tar.gz"
echo "  cd python-offline-debian-aarch64"
echo "  sudo ./install_script/install.sh"